<template>
	<view :class="currentTheme">
		<a-nabbar name="结算" />
		<view class="u-padding-32">
			<view class="u-margin-bottom-20" v-if="option.type != 'ticket'">
				<item-box @click.native="selectAddress" :padding="32">
					<view class="u-text-center" v-if="!showAddress">
						<view class="empty-icon u-flex u-row-center"><u-icon name="plus" size="30" :color="currentThemeObj.primary"></u-icon></view>
						<view class="text-color-DEDEDE u-font-30 u-margin-top-30">暂无地址，请添加</view>
						<!-- <u-icon name="arrow-right" size="36" color="#6C50FE"></u-icon> -->
					</view>
					<view class="u-flex u-row-between" v-else>
						<view class="u-flex-1"><vAddress :item="address"></vAddress></view>
						<u-icon name="arrow-right" size="36" color="#6C50FE" class="u-margin-left-20"></u-icon>
					</view>
				</item-box>
			</view>
			<view class="data-list" v-for="(item, index) in dataList" :key="index">
				<item-box padding="0">
					<view class="u-padding-10">
						<!-- <view class="u-font-20 text-color-B0B2D8 u-margin-top-10 u-margin-bottom-10 u-padding-14">发行名：{{item.name}}</view> -->
						<list-item :item="val" :isTag="false" :showStar="false" padding="0" v-for="(val, i) in item.list" :key="i" :isShare="false" width="214" height="292" :showTime="false">
							<view v-if="val.type === '1111'" class="double-eleven u-position-absolute" slot="imageFixed">
								<item-image img="https://larp-gbo.oss-cn-chengdu.aliyuncs.com/wx/1111tag.png" :width="60" :height="30" :radius="0"></item-image>
							</view>
							<view slot="content" style="width: 100%;height: 15vh;">
								<view class="u-font-24 text-order-time u-margin-top-20">库存：{{ val.stock }}</view>
							</view>
							<view class="u-flex u-row-between u-flex-1" slot="footer">
								<template v-if="!isGroupBuy">
									<view class="u-flex">
										<!-- <text class="text-bold u-font-36 text-color-765CFE">￥{{val.exhibitPrice || 0}}</text> -->
										<!-- 这个不是展会价格 这个字段的实际意思是实际价格的单价 -->
										<money :price="val.exhibitPrice" size="36" :color="currentThemeObj.primary"></money>
									</view>
									<view class="text-color-B0B2D8 u-font-26" v-if="val.num === 0">该商品不可购买</view>
									<view v-else class="text-white">
										<!-- x{{val.num}} -->
										<number-box
											v-model="val.number"
											:num="val.num"
											:index="i"
											:inputHeight="40"
											:min="1"
											:max="val.grantNumber || 99999"
											@change="getInputChange"
											bgColor="white"
											color="#765CFE"
											:disabledInput="!!val.experienceProductId" 
											:disabled="!!val.experienceProductId"
										/>
									</view>
								</template>
								<template v-if="isGroupBuy">
									<view class="u-font-30 text-color-765CFE">x{{ val.num }}</view>
								</template>
							</view>
						</list-item>
						<!-- <view class="u-flex u-padding-left-25 u-padding-right-25  space-between align-center empty-address"  
						v-if="!isGroupBuy">
							<text class="text-color-DEDEDE u-font-28 u-margin-right-10">留言</text>
							<view class="u-flex-1 diy-input">
								<u-input v-model="item.mark" placeholder="给商家留言" input-align="right" :clearable="false" class="text-color-DEDEDE" maxlength="30"></u-input>
							</view>
						</view> -->
						<view class="u-margin-left-24 u-margin-right-24 u-padding-bottom-30">
							<view v-if="isDeposit">
								<view class="u-flex u-row-between  u-margin-top-16">
									<view class="u-flex">
										<view class="content-title-circle"></view>
										<view class="u-font-30 text-color-txtTheme">定金（待付款）</view>
									</view>
									<money :price="totalDeposit" size="36" :color="currentThemeObj.primary"></money>
								</view>
								<view class="u-flex u-row-between u-padding-top-46 content-title u-position-relative">
									<view class="u-flex">
										<view class="content-title-circle"></view>
										<text class="u-font-30 text-bold box-title">尾款</text>
									</view>
									<money :price="balance" size="36"></money>
								</view>
							</view>
							<view v-else>
								<view class="u-flex u-row-between u-margin-top-16">
									<view class="u-font-30 box-title">商品金额：</view>
									<money :price="totalCost" size="36"></money>
								</view>
								<view class="u-flex u-row-between text-tips u-margin-top-16" v-if="option.type != 'ticket'">
									<text class="u-font-24">运费 (运重：10.00 kg)：</text>
									<money :price="0" size="36" color="#808080"></money>
								</view>
								<view class="u-flex text-color-DEDEDE u-margin-top-16 u-col-top" v-if="activityDesc">
									<text class="u-font-24">备注：</text>
									<text class="u-font-24 u-flex-1 text-color-B0B2D8">{{ activityDesc }}</text>
								</view>
							</view>
							<!-- <view class="u-text-right u-margin-top-50 u-margin-bottom-22 u-flex u-row-right">
								<text class="u-font-30 box-title">已优惠：</text>
								<money :price="calcPrice" size="36" :color="currentThemeObj.primary"></money>
							</view> -->
						</view>
					</view>
				</item-box>
			</view>
		</view>
		<fixed-team>
			<!-- 非定金产品 -->
			<view class="u-flex-1 u-flex u-row-between" v-if="!isDeposit">
				<view class="u-flex u-col-top">
					<view>
						<text class="color-80 u-font-20">共{{ count }}件商品,</text>
						<text class="box-title text-bold u-font-32">合计：</text>
					</view>
					<view>
						<money :price="totalPriceNum" size="40" :color="currentThemeObj.primary"></money>
						<view class="u-font-20 text-color-txtTheme">已优惠:￥{{ calcPrice }}</view>
					</view>
				</view>
				<view class="u-padding-left-64">
					<item-btn @click="onSubmit" width="268" height="88">{{ isGroupBuy ? '提交订单' : '去支付' }}</item-btn>
				</view>
			</view>
			<!-- 定金产品 -->
			<view class="u-flex-1" v-if="isDeposit">
				<item-btn @click="onSubmit" width="100%" height="88">
					立即支付定金 ¥
					<text class="u-font-40 u-margin-left-10">{{ totalDeposit }}</text>
				</item-btn>
			</view>
		</fixed-team>
	</view>
</template>

<script>
import vAddress from '@/pagesA/acomponents/address/address.vue';
import { getDetail, getList, add, customRequest } from '@/api/crud.js';
import { mapGetters } from 'vuex';
import { BigNumber } from 'bignumber.js';
import loginMixins from '@/pagesA/login/login.js';
import numberBox from '@/components/numberBox/numberBox.vue';
export default {
	mixins: [loginMixins],
	components: {
		vAddress,
		numberBox
	},
	data() {
		return {
			showAddress: false,
			dataList: [],
			address: {},
			apiType: 'storeOrder',
			apiModule: 'shopApi',
			count: 0,
			totalPriceNum: 0,
			option: {},
			totalCost: 0,
			calcPrice: 0,
			activityDesc: '',
			isDeposit: false, //是否为定金商品
			totalDeposit: '', //定金金额
			balance: '', //尾款金额
			isExperience:false
		};
	},
	computed: {
		...mapGetters(['loginForm']),
		isGroupBuy() {
			return this.option.type === 'groupBuy';
		},
		cartInfoList() {
			const cartInfoList = [];
			this.dataList.forEach(val => {
				val.list.forEach(item => {
					cartInfoList.push({
						productId: item.productId,
						productNum: item.number,
						mallProductId: item.mallProductId,
						experienceProductId:item.experienceProductId,
						mark: val.mark
					});
				});
			});
			return cartInfoList;
		}
	},
	onLoad(option) {
		uni.$on('select', res => {
			this.showAddress = true;
			this.address = res;
		});
		this.option = option;
		console.log(option,'options')
		getDetail(option, this.apiType, this.apiModule, 'getTemp').then(res => {
			res.forEach(item => {
				item.list = item.list.map(val => {
					const cartInfo = JSON.parse(val.cartInfo);
					this.count += val.productNum;
					val.num = val.grantNumber || val.productNum || 1;
					val.number = val.num
					return { ...val, ...cartInfo };
				});
			});
			this.dataList = res;
			this.getInputChange();
		});
		//获取默认地址
		getList(
			{
				uid: this.loginForm.uid
			},
			'userAddress',
			'shopApi',
			'list'
		).then(res => {
			const address = res.find(val => val.isDefault);
			this.address = address || {};
			this.showAddress = !!address;
		});
		uni.$on('payMoney', res => {
			console.log(res);
			uni.hideLoading();
			res.uid == this.loginForm.uid && this.navtoFlag(1);
		});
	},
	destroyed() {
		uni.$off('payMoney');
		uni.$off('select');
	},
	methods: {
		//获取当前总价
		getInputChange(e) {
			// this.totalPriceNum = 0;
			// const initialValue = 0;
			// this.totalPriceNum = this.dataList.reduce((total,next)=>{
			// 	const totalPrice = BigNumber(this.totalPrice(next))
			// 	const plus = totalPrice.plus(total)
			// 	return plus.toNumber();
			// },initialValue)
			this.calculateOrderMoney();
		},
		// 获取当前订单的价格 不用自己算了
		async calculateOrderMoney() {
			const data = await add({ cartInfoList: this.cartInfoList }, 'storeOrder', this.apiModule, 'calculateOrderMoney');
			this.totalPriceNum = data.totalPrice; // 优惠后的付款价格
			this.totalCost = data.totalCost; // 原价
			// this.calcPrice = BigNumber(data.totalCost)
			// 	.minus(data.totalPrice)
			// 	.toNumber(); // 优惠价格
		  this.calcPrice = BigNumber(data.totalDiscount).toNumber();
			this.activityDesc = data.activityDesc; //活动备注
			this.isDeposit = data.isDeposit; //是否为定金商品
			this.totalDeposit = data.totalDeposit; //定金金额
			if (this.isDeposit)
				this.balance = BigNumber(data.totalCost)
					.minus(data.totalDeposit)
					.toNumber();
		},
		async onSubmit() {
			if (!this.totalPriceNum) {
				this.$u.toast('支付金额为0不能购买');
				return false;
			}
			if (!this.address.realName && this.option.type != 'ticket') {
				this.$u.toast('请先添加收货地址');
				return false;
			}
			//更新预付款订单
			const orderId = await add({ cartInfoList: this.cartInfoList }, 'storeOrder', this.apiModule, 'createTemp');
			const form = {
				cartInfoList: this.cartInfoList,
				orderId,
				isChannel: 1,
				realName: this.address.realName,
				shippingType: 1,
				uid: this.loginForm.uid,
				payType: 'weixin',
				mark: '',
				userAddress: this.address.province + this.address.city + this.address.district + this.address.detail,
				userPhone: this.address.phone,
				totalNum: this.count,
				totalPrice: this.totalPriceNum,
				userAddressId: this.address.id
			};
			try {
				await add(form, this.apiType, this.apiModule);
				const code = await this.getLoginCode();
				let codeData = { code, payType: 'weixin', platformType: 'manage' };
				const data = await customRequest(codeData, this.apiType, this.apiModule, 'payMoney/' + orderId, 'post');
				uni.showLoading({
					mask: true,
					title: '支付中...'
				});
				uni.requestPayment({
					//微信支付
					provider: 'wxpay',
					...data,
					success: res => {
						// console.log(res,'支付成功!')
						// if(res && res.errMsg === "requestPayment:ok") {
						// 	this.$u.toast('支付成功!');
						// 	if(this.option.type !== 'ticket') {
						// 		setTimeout(()=> {
						// 			this.$u.route({
						// 				url:`/pagesA/order/order`
						// 			})
						// 		}, 1000)
						// 	}
						// 	if(this.option.type === 'ticket') {
						// 		setTimeout(()=> {
						// 			this.$u.route({
						// 				url:`/pagesA/order/order`,
						// 				params:{
						// 					type:'ticket'
						// 				}
						// 			})
						// 		}, 1000)
						// 	}
						// }
					},
					fail: ({ errMsg }) => {
						errMsg === 'requestPayment:fail cancel' ? this.$u.toast('已取消支付') : this.navtoFlag(0);
					},
					complete: () => {
						uni.hideLoading();
					}
				});
			} catch (e) {
				// uni.hideLoading()
				// this.navtoFlag(0)
				//TODO handle the exception
			}
		},
		navtoFlag(flag) {
			const title = flag == 1 ? '支付成功' : '支付失败';
			this.$u.toast(title);
			this.$u.route({
				type: 'redirectTo',
				url: '/pagesA/success/success',
				params: {
					flag,
					title,
					type: this.option.type
				}
			});
		},
		selectAddress() {
			this.$u.route({
				url: '/pagesB/address/address',
				params: {
					type: 'select'
				}
			});
		},
		totalPrice(item) {
			const initialValue = 0;
			const price = item.list.reduce((total, next) => {
				let { exhibitPrice, num, depositPrice } = next;
				exhibitPrice = depositPrice ? BigNumber(depositPrice) : BigNumber(exhibitPrice);
				const plus = exhibitPrice.multipliedBy(num).plus(total);
				return plus.toNumber();
			}, initialValue);
			//this.totalPriceNum +=price
			return price || 0;
		}
	}
};
</script>

<style lang="scss" scoped>
.empty-address {
	background: #2b2649;
	border: 1px solid #4a3b97;
	margin: 30rpx 12rpx;
	&.not-bg {
		background: transparent;
	}
}
.van-submit-bar-empty {
	height: 200rpx;
}
.bottom-submit {
	border-top: 1rpx solid transparentize($color: #bfbfbf, $amount: 0.4);
	left: 0;
	right: 0;
	bottom: 0;
	padding-left: 64rpx;
	padding-right: 13rpx;
	background-color: #161324;
	padding-bottom: 20rpx;
	line-height: 100rpx;
	.price-tips {
		color: #ececec;
		font-size: 24rpx;
	}
}
.empty-address {
	.u-input.text-color-DEDEDE {
		background-color: transparent;
	}
}
.data-list /deep/ {
	.right-col {
		min-height: auto !important;
	}
	.u-number-input {
		background:var(--background-three-color) !important;
		border:1px solid var(--border-color) ;
		border-radius: 8rpx;
		color: var(--reversal-color) !important;
	}
	.u-icon-disabled {
		background: none !important;
	}
	.content-title-circle {
		width: 20rpx;
		height: 20rpx;
		margin-right: 15rpx;
		border-radius: 50%;
		background-color: rgba($color: #000000, $alpha: 0.1);
	}
	.content-title {
		&::after {
			content: '';
			position: absolute;
			width: 1rpx;
			height: 48rpx;
			background: rgba($color: #000000, $alpha: 0.1);
			top: 0;
			left: 9rpx;
		}
	}
}
</style>
